package com.oauth.google.server.orkut;

import org.springframework.beans.factory.annotation.Required;

import com.oauth.common.server.OAuthGwtController;
import com.oauth.common.server.beans.OAuthAccessToken;
import com.oauth.common.server.beans.OAuthRequestToken;
import com.oauth.common.server.util.OAuthRequestUtil;
import com.oauth.components.client.beans.OAuthUrl;
import com.oauth.components.client.rpc.exception.SessionExpiredException;
import com.oauth.google.client.beans.orkut.GoogleOrkutModel;
import com.oauth.google.client.beans.orkut.HttpQueryString;
import com.oauth.google.client.beans.orkut.OrkutBirthdayDetails;
import com.oauth.google.client.beans.orkut.OrkutFriendDetails;
import com.oauth.google.client.beans.orkut.OrkutScrapDetails;
import com.oauth.google.client.beans.orkut.OrkutUser;
import com.oauth.google.client.exception.GoogleOAuthException;
import com.oauth.google.client.rpc.orkut.OrkutRemoteService;
import com.oauth.google.server.beans.GoogleRequestToken;
import com.oauth.google.server.constants.GoogleConstants;
import com.oauth.google.server.orkut.service.OrkutOAuthService;
import com.oauth.logging.OAuthLogger;

public class GoogleOrkutController extends OAuthGwtController implements OrkutRemoteService {

	private static final long serialVersionUID = -5758464341967618224L;
	private OrkutOAuthService mOrkutOAuthService;
	private OAuthLogger logger = OAuthLogger.getLogger(this.getClass());

	/**
	 * @param pOrkutOAuthService
	 *            the orkutOAuthService to set
	 */
	@Required
	public void setOrkutOAuthService(OrkutOAuthService pOrkutOAuthService) {
		mOrkutOAuthService = pOrkutOAuthService;
	}

	@Override
	public OAuthUrl getSignInUrl() throws GoogleOAuthException {
		GoogleRequestToken requestToken;
		try {
			requestToken = mOrkutOAuthService.getRequestToken();
		} catch (Exception e) {
			logger.error("Error in getting request token", e);
			throw new GoogleOAuthException();
		}
		OAuthRequestUtil.createTokenCookies(getHttpResponse(), requestToken,
				GoogleConstants.ORKUT_TOKEN_COOKIE, GoogleConstants.ORKUT_TOKEN_SECRETCOOKIE);
		OAuthUrl oauthUrl = new OAuthUrl();
		oauthUrl.setOAuthUrl(requestToken.getAuthorizationUrl());
		return oauthUrl;
	}

	public GoogleOrkutModel getOrkutData(HttpQueryString pQueryString) throws GoogleOAuthException {
		System.out.println("Entering Google Orkut HomeController...");

		GoogleOrkutModel model = new GoogleOrkutModel();
		Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
		try {
			OAuthAccessToken accessToken = mOrkutOAuthService.getAccessTokenFromDB(memberId);
			if (accessToken == null) {
				/* Get request token from cookie. */
				OAuthRequestToken requestToken = OAuthRequestUtil.getOAuthTokenFromCookie(
						getHttpRequest(), GoogleConstants.ORKUT_TOKEN_COOKIE,
						GoogleConstants.ORKUT_TOKEN_SECRETCOOKIE);
				if (requestToken == null) {
					model.setLoginView(true);
					return model;// Go to login page, as there is no access
					// token in
					// db and no cookie.
				} else {
					accessToken = mOrkutOAuthService.getAccessTokenFromRequestToken(requestToken,
							pQueryString.getQueryString());

					/* Store access token for future use */
					mOrkutOAuthService.persistAccessToken(accessToken, memberId);
					deleteGoogleCookies();
				}
			}
			// finally you got the access token which is stored in db.
			OrkutUser user = getLoggedInUserInfo();
			model.setUser(user);
			return model;
		} catch (Exception e) {
			deleteGoogleCookies();
			e.printStackTrace();
			logger.error("Error in fetching orkut home data", e);
			throw new GoogleOAuthException();
		}
	}

	private void deleteGoogleCookies() {
		OAuthRequestUtil.deleteTokenCookies(getHttpResponse(), GoogleConstants.ORKUT_TOKEN_COOKIE,
				GoogleConstants.ORKUT_TOKEN_SECRETCOOKIE);
	}

	public OrkutBirthdayDetails getOrkutBirthdays() throws GoogleOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
			OrkutBirthdayDetails birthday = mOrkutOAuthService.getUpcomingBirthdays(memberId);
			logger.debug("Entering birthdays");
			return birthday;
		} catch (Exception e) {
			logger.error("Error in fetching birthdays", e);
			throw new GoogleOAuthException();
		}
	}

	public OrkutScrapDetails getOrkutScraps() throws GoogleOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
			OrkutScrapDetails scraps = mOrkutOAuthService.getScraps(memberId);
			return scraps;
		} catch (Exception e) {
			logger.error("Error in fetching scraps", e);
			throw new GoogleOAuthException();
		}
	}

	public OrkutFriendDetails getOrkutFriends() throws GoogleOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
			OrkutFriendDetails friends = mOrkutOAuthService.getFriends(memberId);
			return friends;
		} catch (Exception e) {
			logger.error("Error in fetching orkut friends", e);
			throw new GoogleOAuthException();
		}

	}

	public OrkutUser getLoggedInUserInfo() throws GoogleOAuthException {
		try {
			Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
			OrkutUser profile = mOrkutOAuthService.getLoggedInUserInfo(memberId);
			logger.info(profile.toString());
			return profile;
		} catch (Exception e) {
			logger.error("Error in fetching orkut user info", e);
			throw new GoogleOAuthException();
		}
	}

	@Override
	public void updateStatus(String pStatusText) throws SessionExpiredException,
			GoogleOAuthException {
		Long memberId = OAuthRequestUtil.getMemberId(getHttpRequest());
		try {
			mOrkutOAuthService.updateStatus(pStatusText, memberId);
		} catch (Exception e) {
			logger.error("Error in updating orkut user status for member=" + memberId, e);
			throw new GoogleOAuthException();
		}
	}

}
